package com.edu.controller;

import com.edu.bean.User;
import com.edu.service.UserService;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.File;
import java.io.IOException;
import java.util.List;

/**
 * @Author:何包蛋
 * @Date :2022/12/7 - 12 - 07 - 18:16
 */
@Controller
public class UserController {

    @Resource
    private UserService userService;

    @RequestMapping("/register")
    public String register(String userName , String password , MultipartFile myFile, Model model) throws IOException {
        String str = myFile.getContentType();
        String type = str.substring(0,str.indexOf("/"));
        if (type.equals("image")){
            String realPath = "E:\\imgs";
            File folder =  new File(realPath);
            if (!folder.exists()){
                folder.mkdirs();
            }
            String headUrl = System.currentTimeMillis()+myFile.getOriginalFilename().substring(myFile.getOriginalFilename().indexOf("."));
            File desFile = new File(realPath,headUrl);
            myFile.transferTo(desFile);
            User user = new User(userName,password,headUrl);
            userService.addUser(user);
            List<User> users = userService.getUserAll();

            model.addAttribute("users",users);
            return "user.jsp";
        }else{
            model.addAttribute("msg","上传类型不合");
            return "register.jsp";
        }



    }

    @RequestMapping("/login")
    public String login(User user,Model model){
        User user1 = userService.getUserByName(user.getUserName());
        if (user1!=null){
            if (user1.getPassword().equals(user.getPassword())){
                List<User> users = userService.getUserAll();
                model.addAttribute("users",users);
                return "user.jsp";
            }else{
                model.addAttribute("msg","密码错误");
                return "login.jsp";
            }
        }else {
            model.addAttribute("msg","用户名不存在");
            return "login.jsp";

        }

    }

}
